<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script src="./lib/vue.js"></script>
</body>

</html>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./lib/vue.js"></script>
</head>

<body>
  <div id="app">
    <input type="text" v-phone v-model="phone">
  </div>

  <script>
    // 定义一个全局自定义指令
    // 自定义指令中不能操作vue中的方法和数据源
    // Vue.directive('自定义指令名称不要加v-',对象[若5个函数方法(钩子函数)]或函数)
    /* Vue.directive('phone', {
      // 绑定时方法
      bind(el) {
        // 得到表单中的数据
        let value = el.value
        if (!/^1[3-9]\d{9}$/.test(value)) {
          el.style.color = 'red'
        }
      },
      update(el) {
        let value = el.value
        if (!/^1[3-9]\d{9}$/.test(value)) {
          el.style.color = 'red'
          if (el.parentNode.lastChild.nodeName !== 'SPAN') {
            let span = document.createElement('span')
            span.innerHTML = '手机号码不合法'
            el.parentNode.appendChild(span)
          }
        } else {
          el.style.color = '#000'
          el.parentNode.removeChild(el.parentNode.lastChild)
        }
      }
    }) */

    // 参数2要是为函数时，则表示这bind和update
    Vue.directive('phone', function (el) {
      let value = el.value
      if (!/^1[3-9]\d{9}$/.test(value)) {
        el.style.color = 'red'
        if (el.parentNode.lastChild.nodeName !== 'SPAN') {
          let span = document.createElement('span')
          span.innerHTML = '手机号码不合法'
          el.parentNode.appendChild(span)
        }
      } else {
        el.style.color = '#000'
        el.parentNode && el.parentNode.lastChild && el.parentNode.removeChild(el.parentNode.lastChild)
      }
    })

    let vm = new Vue({
      el: '#app',
      data: {
        phone: '13821521251',
      }
    })
  </script>
</body>

</html>